# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/07/16 16:48
# @File           : views.py
# @IDE            : PyCharm
# @desc           : 模拟调度组件交互接口

from typing import List
from fastapi import APIRouter, Depends

from apps.base.auth.validate import Auth, AllUserAuth
from apps.base.mock.dispatch import params, schemas
from utils.response import SuccessResponse
from utils.excel.excel_manage import ExcelManage
from .crud import GenerateMockData

app = APIRouter()


# 工单组件接口，工单列表
@app.post("/order/p/cs/v1/queryOrderListPage", summary="模拟工单组件，查询工单列表")
async def get_order_list(
        data: schemas.OrderSearch,
        auth: Auth = Depends(AllUserAuth())
):
     # return {
    #     "data": {
    #         "pageNum": data.pageNum,
    #         "pageSize": data.pageSize,
    #         "pageCount": 1,
    #         "totalRowCount": 20,
    #         "legends": [
    #             {
    #                 "status": "1010",
    #                 "val": "待开工"
    #             },
    #             {
    #                 "status": "1020",
    #                 "val": "工序完成中"
    #             },
    #             {
    #                 "status": "1070",
    #                 "val": "暂停"
    #             },
    #             {
    #                 "status": "1080",
    #                 "val": "撤销中"
    #             },
    #             {
    #                 "status": "1081",
    #                 "val": "墨水更改中"
    #             },
    #             {
    #                 "status": "1098",
    #                 "val": "已撤销"
    #             },
    #             {
    #                 "status": "1099",
    #                 "val": "已归档"
    #             },
    #             {
    #                 "status": "-1",
    #                 "val": "全部"
    #             }
    #         ],
    #         "rows": [
    #         {
    #             "id": 3,
    #             "project": "ARJ21",
    #             "docNum": "200A05EW0080",
    #             "docName": "安装主起舱起落架系统接地桩",
    #             "eff": "10020",
    #             "station": "200",
    #             "position": "200A05",
    #             "serNo": "AO24122805709865",
    #             "orderNum": "00000101023570",
    #             "department": "ARJ事业部",
    #             "orderStatus": "1099",
    #             "aoDistributeDate": "2024-12-02 16:40:54",
    #             "startDate": None,
    #             "startExecutor": None,
    #             "completedDate": None,
    #             "completedExecutor": None,
    #             "isNeedSupervision": 2,
    #             "isNeedPfp": 2,
    #             "isNeedFai": 2,
    #             "isNeedDmir": 2
    #         },
    #         {
    #             "id": 1,
    #             "project": "ARJ21",
    #             "docNum": "200A05EW",
    #             "docName": "安装主起舱起落架系统接地桩123",
    #             "eff": "10015",
    #             "station": "200",
    #             "position": "200A05",
    #             "serNo": "AO24122326841253",
    #             "orderNum": "00000101023569",
    #             "department": "ARJ事业部",
    #             "orderStatus": "1099",
    #             "aoDistributeDate": "2024-12-02 08:39:00",
    #             "startDate": "2024-12-03 02:46:22",
    #             "startExecutor": "zs510122",
    #             "completedDate": None,
    #             "completedExecutor": None,
    #             "isNeedSupervision": 2,
    #             "isNeedPfp": 2,
    #             "isNeedFai": 2,
    #             "isNeedDmir": 2
    #         }
    #     ] + [{
    #             "id": f"{data.pageNum}{i}",
    #             "project": "ARJ21",
    #             "docNum": f"200A05EW008{data.pageNum}{i}",
    #             "docName": f"安装主起舱起落架系统接地桩{data.pageNum}{i}",
    #             "eff": "10015",
    #             "station": "200",
    #             "position": "200A05",
    #             "serNo": f"AO241223268412{data.pageNum}{i}",
    #             "orderNum": f"000001010235{data.pageNum}{i}",
    #             "department": "ARJ事业部",
    #             "orderStatus": "1099",
    #             "aoDistributeDate": "2024-12-02 08:39:00",
    #             "startDate": "2024-12-03 02:46:22",
    #             "startExecutor": "zs510122",
    #             "completedDate": None,
    #             "completedExecutor": None,
    #             "isNeedSupervision": 2,
    #             "isNeedPfp": 2,
    #             "isNeedFai": 2,
    #             "isNeedDmir": 2
    #         } for i in range(10)]
    #     },
    #     "message": None,
    #     "code": 0
    # }

    map_dict = {
        "序号": "id",
        "型号": "project",
        "工艺文件号": "docNum",
        "工艺文件名": "docName",
        "架次": "eff",
        "工位": "station",
        "二级工位": "physicalStation",
        "站位": "position",
        "工单号": "serNo",
        "工单状态": "orderStatus",
        "工单类型": "orderSubType",
        "开工时间": "startDate",
        "归档时间": "completedDate",
        "所需资质": "needSkill",
        "所需人员": "needWorker"
    }

    datas, count = await GenerateMockData().generate_dispatch_mock_data("工单列表", "工单号", map_dict=map_dict, **data.model_dump())

    return {
        "code": 0,
        "message": None,
        "data": {
            "pageNum": data.page,
            "pageSize": data.limit,
            "pageCount": count // data.page + int((count % data.limit) > 0),
            "totalRowCount": count,
            "rows": datas
        }
    }


# 工单组件接口，工单详情
@app.post("/order/p/cs/v1/getOrderDetailDynamic", summary="模拟工单组件，获取工单详情")
async def get_order_detail(
        data: schemas.OrderDetailSearch,
        auth: Auth = Depends(AllUserAuth())
):
    #  {
    #     "code": 0,
    #     "message": "接口请求成果",
    #     "data": {
    #         "baseInfoTable": {
    #             "orderSubType": "AO",
    #             "model":"",
    #             "project": "ARJ21",
    #             "eff": "10015", # 生效架次
    #             "plan_eff": "10015", # 发放架次，对于FO，发放架次与生效架次不一样，对于AO，生效架次=发放架次
    #             "orderNum": "", 
    #             "serNo":  data.serNo, 
    #             "docNum": "200A05EW0080", 
    #             "docName": "安装主起舱起落架系统接地桩", 
    #             "docVer": "002", 
    #             "department": "C919事业部", 
    #             "station": "200", 
    #             "position": "200A05", 
    #             "keyFlag": "", 
    #             "status": "" # 工单状态
    #         }, 
    #         "workInfoTable": {
    #             "data": [
    #                 {
    #                     "workNo": "090", 
    #                     "workDes": "090 安装顶梁支架",        
    #                     "content": "根据工程图样525A1000-000-001及525GD002，按CPS2112，使用高锁螺栓CFBL1001AG5-2（数量4个），安装按CPS9124采用CMS-SL-106 C类12级 密封剂湿安装。（合格证操作）\n\n***注意***\ne、CMS-SL-106 C类12级极限施工12小时。\n\n", 
    #                     "status": "",  # 工序状态
    #                     "pi": [
    #                         {
    #                             "id": "", 
    #                             "piType": "", # 质保标注，适航标注
    #                             "status": "", # pi状态（0:质保，1 适航）
    #                             "questionType": "", # 问题类型
    #                             "isInfluence": "", # 是否影响一次合格提交率（0:不影响，1:影响）
    #                             "isNotNeed": "", # 是否需要制造章（0:不需要，1:需要）
    #                             "deviation": "", # 偏离是否本工序产生  是/否
    #                             "deviationSource": "", # 偏离来源
    #                             "piDesc": "", # pi问题描述
    #                             "relationNo": "", # 关联编号
    #                             "relationDesc": "", # 关联描述
    #                         }
    #                     ]
    #                 },
    #                 {
    #                     "workNo": "105", 
    #                     "workDes": "105 隔音棉开口",        
    #                     "content": "根据工程图样525A1000-000-001及525GD002。（合格证操作）\n\n***注意***\nb、(CMS-PL-908 普通包覆膜（透明）修补时使用普通胶带CMS-AD-208 I型或防火胶CMS-AD-208 II型，CMS-PL-909抗火焰烧穿包覆膜（非透明）修补时使用防火胶带CMS-AD-208 Ⅱ型）。\n\n", 
    #                     "status": "",  # 工序状态
    #                     "pi": [
    #                         {
    #                             "id": "", 
    #                             "piType": "", # 质保标注，适航标注
    #                             "status": "0", # pi状态（0:质保，1 适航）
    #                             "questionType": "", # 问题类型
    #                             "isInfluence": "", # 是否影响一次合格提交率（0:不影响，1:影响）
    #                             "isNotNeed": "", # 是否需要制造章（0:不需要，1:需要）
    #                             "deviation": "", # 偏离是否本工序产生  是/否
    #                             "deviationSource": "", # 偏离来源
    #                             "piDesc": "", # pi问题描述
    #                             "relationNo": "", # 关联编号
    #                             "relationDesc": "", # 关联描述
    #                         }
    #                     ]
    #                 },
    #                 {
    #                     "workNo": "110", 
    #                     "workDes": "110 材料整形",        
    #                     "content": "由8k零件加工中心协助完成", 
    #                     "status": "",  # 工序状态
    #                 }
    #             ]
    #         }
    #     }
    # }
    order_map_dict = {
        "序号": "id",
        "型号": "project",
        "工艺文件号": "docNum",
        "工艺文件名": "docName",
        "架次": "eff",
        "工位": "station",
        "二级工位": "physicalStation",
        "站位": "position",
        "工单号": "serNo",
        "工单状态": "orderStatus",
        "工单类型": "orderSubType",
        "所需资质": "needSkill",
        "所需人员": "needWorker"
    }
    order_work_map_dict = {
        "序号": "id",
        "工单号": "serNo",
        "工序号": "workNo",
        "工序标题": "workDes",
        "工序内容": "content",
        "工序状态": "status",
        "是否有质保标注": "pi"
    }
    params = data.model_dump()
    baseInfoTable, workInfoTable = {}, []
    datas, count = await GenerateMockData().generate_dispatch_mock_data("工单列表", "工单号", map_dict=order_map_dict, **params)
    if datas:
        baseInfoTable = datas[0]
    
    if baseInfoTable:
        datas, count = await GenerateMockData().generate_dispatch_mock_data("工单工序", map_dict=order_work_map_dict, **params)
        if datas:
            workInfoTable = datas

    return {
        "code": 0,
        "message": "接口请求成果",
        "data": {
            "baseInfoTable": baseInfoTable,
            "workInfoTable": {
                "data": workInfoTable
            }
        }
    }


# 计划组件接口，周计划列表
@app.post("/plan/weekListQuery", summary="模拟计划组件，查询周计划列表")
async def get_week_plan(
        data: schemas.PlanSearch,
        auth: Auth = Depends(AllUserAuth())
):
    # return {
    #     "total": 200,
    #     "data": [
    #         {
    #             "model": data.model,
    #             "msn": data.msnStart,
    #             "factory": "",
    #             "productionLine": "",
    #             "station": "223",
    #             "physicalStation": "223A",
    #             "sapOrderNumber": "0000123456789",
    #             "orderType": "AO",
    #             "orderIdentifier": "AO24122326841253",
    #             "docNumber": "223ACS00234",
    #             "docName": "机翼组装",
    #             "startDate": "2024-09-23",
    #             "endDate": "2024-10-23",
    #             "workgroupName": "班组A1",
    #             "workgroupLeader": "组长A(333333)",
    #             "creator": "张三(222222)",
    #             "createdTime": "2024-08-23 10:20:30",
    #             "modifier": "张三(222222)",
    #             "updatedTime": "2024-08-24 11:20:30"
    #         }
    #     ]
    # }

    map_dict = {
        "序号": "id",
        "工单号": "orderIdentifier",
        "工单类型": "orderType",
        "型号": "model",
        "架次": "msn",
        "工位": "station",
        "二级工位": "physicalStation",
        "起始日期": "startDate",
        "结束日期": "endDate",
        "班组号": "workgroupCode",
        "班组名": "workgroupName",
        "班组长": "workgroupLeader",
        "计划人员": "creator",
        "计划时间": "createdTime"
    }

    datas, count = await GenerateMockData().generate_dispatch_mock_data("周计划列表", "工单号", map_dict=map_dict, **data.model_dump())

    return {
        "total": count,
        "data": datas
    }


# 计划组件接口，日计划列表
@app.post("/plan/dayListQuery", summary="模拟计划组件，查询日计划列表")
async def get_day_plan(
        data: schemas.PlanSearch,
        auth: Auth = Depends(AllUserAuth())
):
    # return {
    #     "total": 200,
    #     "data": [
    #         {
    #             "model": data.model,
    #             "msn": data.msnStart,
    #             "factory": "",
    #             "productionLine": "",
    #             "station": "223",
    #             "physicalStation": "223A",
    #             "sapOrderNumber": "0000123456789",
    #             "orderType": "AO",
    #             "orderIdentifier": "AO24122326841253",
    #             "docNumber": "223ACS00234",
    #             "docName": "机翼组装",
    #             "startDate": "2024-09-23",
    #             "endDate": "2024-10-23",
    #             "workgroupName": "班组A1",
    #             "workgroupLeader": "组长A(333333)",
    #             "creator": "张三(222222)",
    #             "createdTime": "2024-08-23 10:20:30",
    #             "modifier": "张三(222222)",
    #             "updatedTime": "2024-08-24 11:20:30"
    #         }
    #     ]
    # }

    map_dict = {
        "序号": "id",
        "工单号": "orderIdentifier",
        "工单类型": "orderType",
        "型号": "model",
        "架次": "msn",
        "工位": "station",
        "二级工位": "physicalStation",
        "起始日期": "startDate",
        "结束日期": "endDate",
        "班组号": "workgroupCode",
        "班组名": "workgroupName",
        "班组长": "workgroupLeader",
        "计划人员": "creator",
        "计划时间": "createdTime"
    }

    datas, count = await GenerateMockData().generate_dispatch_mock_data("日计划列表", "工单号", map_dict=map_dict, **data.model_dump())

    return {
        "total": count,
        "data": datas
    }


# 物流组件接口，配送通知
@app.post("/delivery/deliverMessageQuery", summary="模拟物流组件，查询配送通知")
async def get_delivery_message(
        data: List[schemas.DeliverMessageSearch],
        auth: Auth = Depends(AllUserAuth())
):
    # return {
    #     "code": "0",
    #     "data": [
    #         {
    #             "hasExist": False,
    #             "planNo": "BLJH2024000001",
    #             "serNo": d.serNo,
    #             "project":  "",
    #             "orderType": "工单类型"
    #         } for i, d in enumerate(data)
    #     ],
    #     "message": "",
    # }

    map_dict = {
        "序号": "id",
        "工单类型": "orderType",
        "型号": "project",
        "工单号": "serNo",
        "是否有配送通知": "hasExist"
    }
    results = []
    for search in data:
        r, _ = await GenerateMockData().generate_dispatch_mock_data("物流配送通知", "工单号", map_dict=map_dict, **search.model_dump())
        results.extend(r)

    return {
        "code": "0",
        "data": results,
        "message": ""
    }


# 物流组件接口，物流状态
@app.post("/delivery/deliverStatusQuery", summary="模拟物流组件，查询配送状态")
async def get_delivery_status(
        data: List[schemas.DeliverStatusSearch],
        auth: Auth = Depends(AllUserAuth())
):
    # return {
    #     "code": 0,
    #     "data": [
    #         {
    #             "serNo": d.serNo,
    #             "result": False,
    #             "message": "BLHU0000001-01" if bool(i % 2) else None
    #         } for i, d in enumerate(data) 
    #     ],
    #     "message": "查询成功/异常消息信息"
    # }

    map_dict = {
        "序号": "id",
        "工单号": "serNo",
        "是否成功配送": "result"
    }
    results = []
    for search in data:
        r, _ = await GenerateMockData().generate_dispatch_mock_data("物流配送状态", "工单号", map_dict=map_dict, **search.model_dump())
        results.extend(r)

    return {
        "code": "0",
        "data": results,
        "message": ""
    }


# 基础数据接口文档1209版本：22人员岗位部门映射列表
@app.post("/data/PjMappingQuery", summary="模拟人员资质组件，查询人员岗位部门映射列表")
async def get_emp_users(
        data: schemas.TeamUserSearch,
        auth: Auth = Depends(AllUserAuth())
):
    # return {
    #     "data": [
    #         {
    #             "id": 1,
    #             "jobNo": "333658",
    #             "jobCode": data.jobCode or "00335563",
    #             "deptCode": "05203604",
    #             "priority": None,
    #             "isValid": 1,
    #             "userName": "李子" + data.pageIndex,
    #             "jobName": "适航审核计划师" + data.jobCode,
    #             "deptName": "计划管理室"
    #         },
    #         {
    #             "id": 1,
    #             "jobNo": "333659",
    #             "jobCode": data.jobCode or "00335563",
    #             "deptCode": "05203604",
    #             "priority": None,
    #             "isValid": 1,
    #             "userName": "张三" + data.pageIndex,
    #             "jobName": "适航审核计划师" + data.jobCode,
    #             "deptName": "计划管理室"
    #         }
    #     ],
    #     "message": "",
    #     "total": "3170",
    #     "code": 0
    # }

    map_dict = {
        "序号": "id",
        "工号": "jobNo",
        "班组号": "jobCode",
        "姓名": "userName",
        "岗位名": "jobName",
        "部门号": "deptCode",
        "部门名": "deptName",
        "资质": "skill",
        "技能等级": "level"
    }

    datas, count = await GenerateMockData().generate_dispatch_mock_data("班组用户", map_dict=map_dict, **data.model_dump())
    return {
        "total": count,
        "code": 0,
        "message": "",
        "data": datas
    }

# 基础数据接口文档1209版本：38班组列表
@app.post("/data/GrpListQuery", summary="模拟人员资质组件，查询班组列表")
async def get_emp_groups(
        data: schemas.TeamSearch,
        auth: Auth = Depends(AllUserAuth())
):

    # return {
    #     "data": [
    #         {
    #             "id": 1,
    #             "model": "ARJ21",
    #             "factory": "0",
    #             "plant": None,
    #             "workshop": None,
    #             "code": "55",
    #             "group": data.group,
    #             "isValid": 1
    #         }
    #     ],
    #     "message": "",
    #     "total": "30",
    #     "code": 0
    # }

    map_dict = {
        "序号": "id",
        "型号": "model",
        "班组号": "code",
        "班组名": "group"
    }

    datas, count = await GenerateMockData().generate_dispatch_mock_data("班组列表", map_dict=map_dict, **data.model_dump())

    return {
        "total": count,
        "code": 0,
        "message": "",
        "data": datas
    }
